/*
 * Copyright 2011 Kim Lindhardt Madsen
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package dk.lindhardt.gwt.geie.server.convert;

import dk.lindhardt.gwt.geie.shared.Formula;
import dk.lindhardt.gwt.geie.shared.Position;
import jxl.CellReferenceHelper;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: AnAmuser
 * Date: 13-08-11
 * <p/>
 * Convert back and forth between excel and geie formulas
 */
public class FormulaConverter {

   private final static Pattern excelPattern = Pattern.compile("(\\$?)(\\p{Upper}+)(\\$?)(\\d+)");

   /**
    * Converts a formula to the corresponding excel formula string
    * @param formula the formula
    * @return the excel formula
    */
   public static String convert(Formula formula) {
      Map<String, Position> cellVariables = formula.getCellVariables();
      String formulaString = formula.getFormula();
      for (String variable : cellVariables.keySet()) {
         Position position = cellVariables.get(variable);
         formulaString = formulaString.replace(
               variable, CellReferenceHelper.getCellReference(
               position.getColumn(), position.getRow()));
      }
      return formulaString;
   }

   /**
    * Converts an excel formula into its corresponding formula object.
    * @param formulaString the excel formula
    * @return the formula object
    */
   public static Formula convert(String formulaString) {
      Map<Position, String> usedVariables = new HashMap<Position, String>();

      Matcher matcher = excelPattern.matcher(formulaString);

      StringBuffer buffer = new StringBuffer();
      boolean result = matcher.find();
      while (result) {
         Position position = getPosition(matcher);
         String variable = usedVariables.get(position);
         if (variable == null) {
            variable = "x" + usedVariables.size();
            usedVariables.put(position, variable);
         }
         matcher.appendReplacement(buffer, variable);

         result = matcher.find();
      }
      matcher.appendTail(buffer);

      Formula formula = new Formula(buffer.toString());
      formula.setCellVariables(inverseMap(usedVariables));
      return formula;
   }

   private static Position getPosition(Matcher matcher) {
      String colString = matcher.group(2);
      String rowString = matcher.group(4);
      int row = Integer.parseInt(rowString) - 1;
      int col = CellReferenceHelper.getColumn(colString);
      return new Position(row, col);
   }

   private static Map<String, Position> inverseMap(Map<Position, String> map) {
      Map<String, Position> result = new HashMap<String, Position>();
      for (Position position : map.keySet()) {
         String string = map.get(position);
         result.put(string, position);
      }
      return result;
   }
}